package com.peng.leetcode.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * Flatten
 * 114. 二叉树展开为链表
 * 给定一个二叉树，原地将它展开为一个单链表。
 *
 * @author: lupeng6
 * @create: 2021/1/8 15:24
 */
public class Flatten {

    public static void main(String[] args) {
        Integer[] arr = new Integer[]{1, 2, 5, 3, 4, null, 6};
        TreeNode treeNode = TreeMain.array2tree(arr);
        new Flatten().flatten(treeNode);
        System.out.println(treeNode);
    }

    private List<TreeNode> nodes = new ArrayList<>();

    public void flatten(TreeNode root) {
        preOrder(root);
        for (int i = 1; i < nodes.size(); i++) {
            TreeNode prev = nodes.get(i - 1);
            TreeNode curr = nodes.get(i);
            prev.right = curr;
            prev.left = null;
        }
    }

    public void preOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        nodes.add(root);
        preOrder(root.left);
        preOrder(root.right);
    }

}
